import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RegisterPage } from '../register/register';
import { HttpService } from '../../../service/httpService';
import { FormBuilder }        from '@angular/forms';
import { NativeService } from '../../../service/NativeService';
import { CookieService } from 'ngx-cookie-service';
import { UserService } from '../../../service/userService';
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  private loginForm:any;
  private UserName:string;
  private Password:string;
  constructor(public navCtrl: NavController,
              public http:HttpService,
              public form:FormBuilder,
              public user:UserService,
              public cookie:CookieService,
              public nat:NativeService) {

    this.loginForm = form.group({
      UserName:['test011'],
      Password:['123456'],
      safety:[0],
      comeFrom:['']
    })
  }

  registerAction(){
    this.navCtrl.push(RegisterPage);
  }

  loginAction(loginForm){
    this.UserName = loginForm.UserName;
    this.Password = loginForm.Password;
    loginForm.comeFrom = this.nat.isIos?'iOS':'android';
    this.nat.showLoading('登录中...');
    let url = this.http.baseUrl + "/api/Account/Login";
    let self = this;
    this.http.post(url,loginForm,function (res,err) {
      if(!err){
        if(res.StatusCode){
          self.nat.showToast(res.Message);
        }else {
          console.log(res);
          self.user.access_token = res.access_token;
          self.user.registTime = res.registTime;
          self.user.token_type = res.token_type;
          let obj = {UserName:self.UserName,Password:self.Password};
          localStorage.setItem("authtoken",res.access_token);
          self.getUserInfo();
          self.getUserBankList();
        }
      }else {
        self.nat.hideLoading();
      }
    });
  }

  getUserInfo(){
    // let url = "/api/Account/GetLoginUser";
    let url = "/api/v2/Account/GetLoginUser";
    let self = this;
    this.http.get(url,{},function (res,err) {
      self.nat.hideLoading();
      if(!err){
        console.log(res);
        self.user.setUserInfo(res);
        self.navCtrl.pop();
      }
    })
  }

  getUserBankList(){
    let self = this;
    let url = "/api/User/GetUserBankList";
    this.http.get(url,{},function (res,err) {
      if(!err){
        console.log('获取用户银行成功');
        self.user.banks = res;
      }
    });
  }


}
